const { jwt } = require('../utils')
const { jwtSecret } = require('../config/config.default')
const { User } = require('../model')

module.exports = async (req, res, next) => {
  // 从请求头获取并处理 token Authorization: Bearer token...
  let token = req.headers.authorization
  token = token ? token.split('Bearer ')[1] : null
  if (!token) {
    return res.status(401).end()
  }
  try {
    // jwt 验证
    const decoded = await jwt.verify(token, jwtSecret)
    // 根据 userId 查询用户并保存 user
    req.user = await User.findById(decoded.userId)
    // 往下执行中间件
    next()
  } catch (err) {
    return res.status(401).end()
  }
}
